//
//  UpgradeViewController.swift
//  UILbrary
//
//  Created by 斌 on 2017/8/14.
//  Copyright © 2017年 mac. All rights reserved.
//

//Field Header:
//The text of the subfield is displayed starting on the next line.
import UIKit

class UpgradeViewController: UIViewController {
    /// 自动更新按钮
    var upgradeBtn:UIButton!
    var currentVersion:String!
    
    
    
    
    //MARK: init
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        upgradeBtn = UIButton.init(frame: CGRect.zero)
        upgradeBtn.backgroundColor = UIColor.red
//        upgradeBtn.setTitle("自动更新", for: UIControlState.normal)
//        upgradeBtn.addTarget(self, action: #selector(upgradeBtnClick), for: UIControlEvents.touchUpInside)
        self.view.addSubview(upgradeBtn)
        upgradeBtn.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view.snp.centerX)
            make.centerY.equalTo(self.view.snp.centerY)
            make.size.equalTo(CGSize(width: 100, height: 100))
            //make.left.top.right.bottom.equalTo(100)
        }
        
        // Do any additional setup after loading the view.
    }
    
    func upgradeBtnClick(){
        print("提示跟新")
        checkVerson()
    }
    
    func checkVerson(){
        let infoDictionary = Bundle.main.infoDictionary
        //app 版本
        self.currentVersion = infoDictionary?["CFBundleShortVersionString"] as! String
        if let version: String? = infoDictionary?["CFBundleShortVersionString"] as? String{
            self.currentVersion = version
        }else{
            self.currentVersion = ""
        }
        
        let upgradeUrl = URL.init(string: "http://sz.seasaw.cn:8085/carManager/carManager/helpInfo!update.action?os=0")
        let upgradeRequest = URLRequest.init(url: upgradeUrl!)
        let session = URLSession.shared
        
        let sessionDataTask:URLSessionDataTask = session.dataTask(with: upgradeRequest) { (Data, response, error) in
            if Data != nil {
                var err:NSError?
                do {
                    let dic:NSDictionary = try JSONSerialization.jsonObject(with: Data!, options: [JSONSerialization.ReadingOptions.mutableContainers]) as! NSDictionary
                    let responseContent = NSString.init(data: Data!, encoding: String.Encoding.utf8.rawValue)
                    print(dic.description)
                    print("responseContent: \(String(describing:  responseContent))" )
                    if (dic["result"] as! NSNumber).boolValue == false{
                        
                        
                        self.jumpToAppStore()
                    }
                } catch {
                    print(err?.description)
                }
                
                
            }
            
    
        }
        sessionDataTask.resume()
    }
    
    func showUpgradeView() {
        
    }
    
    
    func jumpToAppStore() {
        //提示升级. 下面是锦讯 App Store 地址
        // 直接跳到 App Store 就好
        //https://itunes.apple.com/us/app/%E9%94%A6%E8%BF%85/id790097387?mt=8
        
//        NSString *urlStr = [self getAppStroeUrlForiPhone];
//        #ifdef __IPHONE_10_0
//        NSDictionary *options = @{UIApplicationOpenURLOptionUniversalLinksOnly : @YES};
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:options completionHandler:^(BOOL success) {
//            
//            }];
//#else
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        //https://itunes.apple.com/us/app/%E9%94%A6%E8%BF%85/id790097387?mt=8
        let appStoreStr = "https://itunes.apple.com/us/app/%E9%94%A6%E8%BF%85/id790097387"
        let appStoreUrl = URL(string: appStoreStr)
#if __IPHONE_10_0
    let options:NSDictionary = [UIApplicationOpenURLOptionUniversalLinksOnly:true]
    
    UIApplication.shared.open(appStoreUrl, options: options, completionHandler: ((Bool) -> Void)?)
#else
        UIApplication.shared.openURL(appStoreUrl!)
#endif
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    /*
     接口返回值
     {
     result = 0;
     "version-info" =     {
     "down_address" = "http://61.144.248.2:9090/upload/apk/JLCar3.5.9.apk";
     "version_name" = "JLCar3.5.9.apk";
     "version_number" = 1091;
     };
     }
     */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
